package com.wwwarehouse.resource_center.fragment.rules;

import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NetUtils;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.eventbus_event.Event;
import com.wwwarehouse.resource_center.eventbus_event.HideTitleBean;
import com.wwwarehouse.resource_center.utils.EventBusUtil;

import java.util.HashMap;
import java.util.Map;

public abstract class TheParentFragment<K, V> extends BaseFragment {

    protected int responseCode = 0;// 标记第N个网络请求
    protected StateLayout mLoadingView;
    protected boolean isShowProgress = true;  //true显示Progress， false显示loading页面，一般情况下第一次进去都是false
    private FrameLayout mContentLayout;
    protected boolean isShow = true;  //重置标题状态

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View mBaseView = inflater.inflate(R.layout.fragment_blank, container, false);
        mLoadingView = (StateLayout) mBaseView.findViewById(R.id.loading);
        mContentLayout = (FrameLayout) mBaseView.findViewById(R.id.content);
        mLoadingView.setVisibility(View.INVISIBLE);
        mContentLayout.addView(inflater.inflate(getContentId(), container, false));
        return mBaseView;
    }
//    public abstract View CreateView(int id, ViewGroup container,boolean flag);

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        init(view);
        loadDatas();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
    }

    public void onEventMainThread(Event event) {
        if (event != null) {
            if (event.getData() instanceof HideTitleBean && event.getCode() == HideTitleBean.CODE.A) {
                isShow = true;
            }
            receiveEvent(event);
        }
    }

    protected void receiveEvent(Event event) {
    }

    protected void loadDatas() {

    }

    protected abstract int getContentId();

    protected abstract void init(View view);

    @Override
    public void setTitle() {

    }

    /**
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话重写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    public void requestDatas() {

    }

    /**
     * 发送网络请求的方法
     *
     * @param mUrl           请求url
     * @param hashMap        请求参数
     * @param code           请求码，不能重复。
     * @param isShowProgress 请求显示的方式,true ShowProgress,false 一般是第一次进去加载显示StateLayout
     * @param msg            Progress内容文字提示
     */
    protected void httpPost(String mUrl, Map<K, V> hashMap, final int code, boolean isShowProgress, String msg) {
        this.isShowProgress = isShowProgress;
        //页面第一次进来需要展示loadingView,此外都是展示progressDialog.
        if (isShowProgress) {
            if (TextUtils.isEmpty(msg)) {
                showProgressDialog("请求中……");
            } else {
                showProgressDialog(msg);
            }
        } else {
            if (mLoadingView != null) {
                mLoadingView.setVisibility(View.VISIBLE);
                if (!NetUtils.isHttpConnected(mActivity)) { //没有网络请求
                    mLoadingView.showNetworkView(true);
                    mLoadingView.setNetworkListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                            onReLoad(code);
                        }
                    });
                    return;
                } else {
                    mLoadingView.showProgressView(true);
                }
            }
        }
        this.responseCode = code;
        if (null == hashMap) {
            hashMap = new HashMap<>();
        }
        NoHttpUtils.httpPost(mUrl, hashMap, mOnLoadListener, responseCode);
    }

    /**
     * 发送网络请求的方法,静默请求网络，Progress，loading都不显示
     *
     * @param mUrl    请求url
     * @param hashMap 请求参数
     * @param code    请求码，不能重复。
     */
    protected void httpPost(String mUrl, Map<K, V> hashMap, final int code) {
        if (!NetUtils.isHttpConnected(mActivity)) { //没有网络请求
            toast("请检查网络连接");
            return;
        }
        this.isShowProgress = true;
        this.responseCode = code;
        if (null == hashMap) {
            hashMap = new HashMap<>();
        }
        NoHttpUtils.httpPost(mUrl, hashMap, mOnLoadListener, responseCode);
    }

    NoHttpUtils.OnResponseListener mOnLoadListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, final int i) {
            if (isShowProgress) {
                mLoadingView.setVisibility(View.GONE);
                mLoadingView.showContentView();
                onSuccess(commonClass, i);
            } else {
                if (TextUtils.equals("0", commonClass.getCode())) {
                    if (commonClass.getData() == null) {
                        mLoadingView.showEmptyView(true);
                        mLoadingView.setEmptyListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mLoadingView.showProgressView(true);
                                onReLoad(i);
                            }
                        });
                    } else {
                        mLoadingView.setVisibility(View.GONE);
                        mLoadingView.showContentView();
                        onSuccess(commonClass, i);
                    }
                } else {
                    mLoadingView.showSystemView(true);
                    mLoadingView.setSystemListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                            onReLoad(i);
                        }
                    });
                }
            }

        }

        @Override
        public void onFailed(String s, final int i) {
            LogUtils.showInfoLog("onFailed:" + s + ":" + i);
            dismissProgressDialog();
            if (!isShowProgress) {
                if (TextUtils.isEmpty(s)) {
                    mLoadingView.showSystemView(true);
                    mLoadingView.setSystemListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                            onReLoad(i);
                        }
                    });
                } else {
                    mLoadingView.showNetworkView(true);
                    mLoadingView.setNetworkListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mLoadingView.showProgressView(true);
                            onReLoad(i);
                        }
                    });
                }
            } else {
                //服务器返回null
            }
        }

        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };

    public abstract void onSuccess(CommonClass commonClass, int what);

    /**
     * 点击重新加载的回调
     *
     * @param code
     */

    public abstract void onReLoad(int code);

    public boolean isNavigationBarShow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = mActivity.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            return realSize.y != size.y;
        } else {
            boolean menu = ViewConfiguration.get(getContext()).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if (menu || back) {
                return false;
            } else {
                return true;
            }
        }
    }

    public int getNavigationBarHeight() {
        if (!isNavigationBarShow()) {
            return 0;
        }
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        //获取NavigationBar的高度
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isShow = true;
        EventBusUtil.sendEvent(new Event(HideTitleBean.CODE.A, new HideTitleBean()));
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this);
        }
        ((BaseCardDeskActivity) mActivity).recoveryTitleBtStatus_4();
        ((BaseCardDeskActivity) mActivity).hideSearchInput();
        ((BaseCardDeskActivity) mActivity).hideSearchTitle();
    }
}
